package com.ruoyi.system.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DbPhysicalManagementMapper;
import com.ruoyi.system.domain.DbPhysicalManagement;
import com.ruoyi.system.domain.ScoreManagement;
import com.ruoyi.system.domain.DbIdentityManagement;
import com.ruoyi.system.service.IDbPhysicalManagementService;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.system.service.IResultManagementService;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.ruoyi.system.domain.dto.StatisticsDTO;
import com.ruoyi.system.domain.dto.StatisticsDTO.PositionData;

/**
 * 四级联考递补体能测评Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class DbPhysicalManagementServiceImpl implements IDbPhysicalManagementService 
{
    private static final Logger log = LoggerFactory.getLogger(DbPhysicalManagementServiceImpl.class);

    @Autowired
    private DbPhysicalManagementMapper dbPhysicalManagementMapper;
    
    @Autowired
    protected Validator validator;
    
    @Autowired
    private IResultManagementService resultManagementService;

    /**
     * 查询四级联考递补体能测试
     * 
     * @param id 四级联考递补体能测试主键
     * @return 四级联考递补体能测试
     */
    @Override
    public DbPhysicalManagement selectDbPhysicalManagementById(Long id)
    {
        return dbPhysicalManagementMapper.selectDbPhysicalManagementById(id);
    }

    /**
     * 查询四级联考递补体能测试列表
     * 
     * @param dbPhysicalManagement 四级联考递补体能测试
     * @return 四级联考递补体能测试
     */
    @Override
    public List<DbPhysicalManagement> selectDbPhysicalManagementList(DbPhysicalManagement dbPhysicalManagement)
    {
        return dbPhysicalManagementMapper.selectDbPhysicalManagementList(dbPhysicalManagement);
    }

    /**
     * 新增四级联考递补体能测试
     * 
     * @param dbPhysicalManagement 四级联考递补体能测试
     * @return 结果
     */
    @Override
    public int insertDbPhysicalManagement(DbPhysicalManagement dbPhysicalManagement)
    {
        return dbPhysicalManagementMapper.insertDbPhysicalManagement(dbPhysicalManagement);
    }

    /**
     * 修改四级联考递补体能测试
     * 
     * @param dbPhysicalManagement 四级联考递补体能测试
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDbPhysicalManagement(DbPhysicalManagement dbPhysicalManagement)
    {
        // 获取原有数据
        DbPhysicalManagement originalData = selectDbPhysicalManagementById(dbPhysicalManagement.getId());
        
        // 执行更新操作
        int rows = dbPhysicalManagementMapper.updateDbPhysicalManagement(dbPhysicalManagement);
        
        // 如果更新成功，且递补体能测评结果从非"通过"变为"通过"，则检查是否需要自动流转到终审结果模块
        if (rows > 0 && "通过".equals(dbPhysicalManagement.getPhysicalTestResult()) 
            && (originalData == null || !"通过".equals(originalData.getPhysicalTestResult())))
        {
            // 获取更新后的完整数据
            DbPhysicalManagement updatedData = selectDbPhysicalManagementById(dbPhysicalManagement.getId());
            
            // 检查递补资格审查和递补身份验证是否都通过
            if ("通过".equals(updatedData.getQualificationReviewResult()) && 
                "通过".equals(updatedData.getIdentityVerificationResult()))
            {
                log.info("递补考生{}（身份证号：{}）递补资格审查、递补身份验证、递补体能测评均已通过，自动流转到终审结果模块", 
                         updatedData.getName(), updatedData.getIdCard());
                
                try
                {
                    // 创建只包含当前考生的列表
                    List<DbPhysicalManagement> qualifiedList = new java.util.ArrayList<>();
                    qualifiedList.add(updatedData);
                    
                    // 设置最终结果为通过
                    updatedData.setFinalResult("通过");
                    dbPhysicalManagementMapper.updateDbPhysicalManagement(updatedData);
                    
                    // 调用终审结果服务，将考生添加到终审结果名单
                    int count = resultManagementService.insertResultListFromDbPhysical(qualifiedList, "系统自动");
                    log.info("递补考生{}（身份证号：{}）成功流转到终审结果模块", 
                             updatedData.getName(), updatedData.getIdCard());
                }
                catch (Exception e)
                {
                    log.error("递补考生流转到终审结果模块失败", e);
                    // 这里不抛出异常，确保即使流转失败，更新操作仍然成功
                }
            }
        }
        
        return rows;
    }

    /**
     * 批量删除四级联考递补体能测试
     * 
     * @param ids 需要删除的四级联考递补体能测试主键
     * @return 结果
     */
    @Override
    public int deleteDbPhysicalManagementByIds(Long[] ids)
    {
        return dbPhysicalManagementMapper.deleteDbPhysicalManagementByIds(ids);
    }

    /**
     * 删除四级联考递补体能测试信息
     * 
     * @param id 四级联考递补体能测试主键
     * @return 结果
     */
    @Override
    public int deleteDbPhysicalManagementById(Long id)
    {
        return dbPhysicalManagementMapper.deleteDbPhysicalManagementById(id);
    }

    /**
     * 导入四级联考递补体能测评数据
     * 
     * @param dbPhysicalList 递补体能测评数据列表
     * @param updateSupport 是否更新支持，如果已存在，是否覆盖
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importDbPhysicalData(List<DbPhysicalManagement> dbPhysicalList, boolean updateSupport, String operName)
    {
        if (StringUtils.isNull(dbPhysicalList) || dbPhysicalList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (DbPhysicalManagement dbPhysical : dbPhysicalList)
        {
            try
            {
                // 验证是否存在相同的准考证号或身份证号
                DbPhysicalManagement existDbPhysical = new DbPhysicalManagement();
                if (StringUtils.isNotEmpty(dbPhysical.getExamNumber()))
                {
                    existDbPhysical.setExamNumber(dbPhysical.getExamNumber());
                }
                else if (StringUtils.isNotEmpty(dbPhysical.getIdCard()))
                {
                    existDbPhysical.setIdCard(dbPhysical.getIdCard());
                }
                else
                {
                    throw new ServiceException("导入数据中准考证号和身份证号不能同时为空");
                }
                
                List<DbPhysicalManagement> existList = dbPhysicalManagementMapper.selectDbPhysicalManagementList(existDbPhysical);
                
                if (StringUtils.isNull(existList) || existList.size() == 0)
                {
                    // 如果不存在，执行插入操作
                    dbPhysicalManagementMapper.insertDbPhysicalManagement(dbPhysical);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + dbPhysical.getExamNumber() + " 导入成功");
                }
                else if (updateSupport)
                {
                    // 如果存在且允许更新
                    dbPhysical.setId(existList.get(0).getId()); // 设置ID，确保更新正确的记录
                    dbPhysicalManagementMapper.updateDbPhysicalManagement(dbPhysical);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + dbPhysical.getExamNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、准考证号 " + dbPhysical.getExamNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、准考证号 " + dbPhysical.getExamNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 从成绩合格名单生成并插入递补体能测试名单
     * 
     * @param scoreList 符合条件的成绩合格名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDbPhysicalListFromScore(List<ScoreManagement> scoreList, String operName)
    {
        if (StringUtils.isNull(scoreList) || scoreList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 先清空现有递补体能测试名单数据
        DbPhysicalManagement clearCriteria = new DbPhysicalManagement();
        List<DbPhysicalManagement> existingList = dbPhysicalManagementMapper.selectDbPhysicalManagementList(clearCriteria);
        if (existingList != null && existingList.size() > 0)
        {
            Long[] ids = new Long[existingList.size()];
            for (int i = 0; i < existingList.size(); i++)
            {
                ids[i] = existingList.get(i).getId();
            }
            dbPhysicalManagementMapper.deleteDbPhysicalManagementByIds(ids);
        }
        
        // 遍历符合条件的考生，插入递补体能测试名单
        for (ScoreManagement score : scoreList)
        {
            try
            {
                // 创建递补体能测试名单对象
                DbPhysicalManagement dbPhysical = new DbPhysicalManagement();
                
                // 复制考生信息
                dbPhysical.setCandidateId(score.getCandidateId());
                dbPhysical.setName(score.getName());
                dbPhysical.setGender(score.getGender());
                dbPhysical.setIdCard(score.getIdCard());
                dbPhysical.setExamNumber(score.getExamNumber());
                dbPhysical.setAdministrativeAptitudeScore(score.getAdministrativeAptitudeScore());
                dbPhysical.setEssayScore(score.getEssayScore());
                dbPhysical.setProfessionalSubjectScore(score.getProfessionalSubjectScore());
                dbPhysical.setTotalScore(score.getTotalScore());
                dbPhysical.setProfessionalSkillTestScore(score.getProfessionalSkillTestScore());
                dbPhysical.setAppliedUnit(score.getAppliedUnit());
                dbPhysical.setAppliedPosition(score.getAppliedPosition());
                dbPhysical.setRecruitmentNumber(score.getRecruitmentNumber());
                dbPhysical.setInterviewRatio(score.getInterviewRatio());
                dbPhysical.setRanking(score.getRanking());
                dbPhysical.setGraduationSchool(score.getGraduationSchool());
                dbPhysical.setHasProfessionalSkillTest(score.getHasProfessionalSkillTest());
                dbPhysical.setPositionCategory(score.getPositionCategory());
                dbPhysical.setIsAlternate("Y");  // 设置为递补
                dbPhysical.setQualificationReviewResult("通过");  // 设置为通过
                dbPhysical.setIdentityVerificationResult("通过");  // 设置为通过
//                dbPhysical.setPhysicalTestResult("待测评");  // 默认为待测评
//                dbPhysical.setFinalResult("待确认");  // 默认为待确认
                
                // 执行插入操作
                dbPhysicalManagementMapper.insertDbPhysicalManagement(dbPhysical);
                successNum++;
            }
            catch (Exception e)
            {
                log.error("插入递补体能测试名单失败，准考证号：" + score.getExamNumber(), e);
            }
        }
        
        return successNum;
    }

    /**
     * 从递补身份验证名单生成并插入递补体能测试名单
     * 
     * @param dbIdentityList 符合条件的递补身份验证名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDbPhysicalListFromDbIdentity(List<DbIdentityManagement> dbIdentityList, String operName)
    {
        if (StringUtils.isNull(dbIdentityList) || dbIdentityList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 先清空现有递补体能测试名单数据
     /*   DbPhysicalManagement clearCriteria = new DbPhysicalManagement();
        List<DbPhysicalManagement> existingList = dbPhysicalManagementMapper.selectDbPhysicalManagementList(clearCriteria);
        if (existingList != null && existingList.size() > 0)
        {
            Long[] ids = new Long[existingList.size()];
            for (int i = 0; i < existingList.size(); i++)
            {
                ids[i] = existingList.get(i).getId();
            }
            dbPhysicalManagementMapper.deleteDbPhysicalManagementByIds(ids);
        }*/
        
        // 遍历符合条件的考生，插入递补体能测试名单
        for (DbIdentityManagement dbIdentity : dbIdentityList)
        {
            try
            {
                // 创建递补体能测试名单对象
                DbPhysicalManagement dbPhysical = new DbPhysicalManagement();
                
                // 复制考生信息
                dbPhysical.setCandidateId(dbIdentity.getCandidateId());
                dbPhysical.setName(dbIdentity.getName());
                dbPhysical.setGender(dbIdentity.getGender());
                dbPhysical.setIdCard(dbIdentity.getIdCard());
                dbPhysical.setExamNumber(dbIdentity.getExamNumber());
                dbPhysical.setAdministrativeAptitudeScore(dbIdentity.getAdministrativeAptitudeScore());
                dbPhysical.setEssayScore(dbIdentity.getEssayScore());
                dbPhysical.setProfessionalSubjectScore(dbIdentity.getProfessionalSubjectScore());
                dbPhysical.setTotalScore(dbIdentity.getTotalScore());
                dbPhysical.setProfessionalSkillTestScore(dbIdentity.getProfessionalSkillTestScore());
                dbPhysical.setAppliedUnit(dbIdentity.getAppliedUnit());
                dbPhysical.setAppliedPosition(dbIdentity.getAppliedPosition());
                dbPhysical.setRecruitmentNumber(dbIdentity.getRecruitmentNumber());
                dbPhysical.setInterviewRatio(dbIdentity.getInterviewRatio());
                dbPhysical.setRanking(dbIdentity.getRanking());
                dbPhysical.setGraduationSchool(dbIdentity.getGraduationSchool());
                dbPhysical.setHasProfessionalSkillTest(dbIdentity.getHasProfessionalSkillTest());
                dbPhysical.setPositionCategory(dbIdentity.getPositionCategory());
                dbPhysical.setIsAlternate("Y");  // 设置为递补
                dbPhysical.setQualificationReviewResult("通过");  // 设置为通过
                dbPhysical.setIdentityVerificationResult("通过");  // 设置为通过
//                dbPhysical.setPhysicalTestResult("待测评");  // 默认为待测评
//                dbPhysical.setFinalResult("待确认");  // 默认为待确认
                
                // 执行插入操作
                dbPhysicalManagementMapper.insertDbPhysicalManagement(dbPhysical);
                successNum++;
            }
            catch (Exception e)
            {
                log.error("递补体能测试名单导入失败：", e);
                throw new ServiceException("导入递补体能测试名单失败，请联系管理员");
            }
        }
        
        return successNum;
    }

    /**
     * 获取四级联考递补体能测试统计数据
     * 
     * @return 统计数据
     */
    @Override
    public StatisticsDTO getDbPhysicalStatistics()
    {
        // 创建返回对象
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        
        // 查询所有递补体能测试数据
        List<DbPhysicalManagement> dbPhysicalList = dbPhysicalManagementMapper.selectDbPhysicalManagementList(new DbPhysicalManagement());
        
        // 总数
        int total = dbPhysicalList.size();
        statisticsDTO.setTotal(total);
        
        // 通过和未通过数量
        int passed = 0;
        // 职位分布统计
        Map<String, Integer> positionMap = new HashMap<>();
        
        for (DbPhysicalManagement dbPhysical : dbPhysicalList)
        {
            // 统计通过人数
            if ("通过".equals(dbPhysical.getPhysicalTestResult()))
            {
                passed++;
            }
            
            // 统计职位分布
            String position = dbPhysical.getAppliedPosition();
            if (position != null && !position.isEmpty())
            {
                positionMap.put(position, positionMap.getOrDefault(position, 0) + 1);
            }
        }
        
        statisticsDTO.setPassed(passed);
        statisticsDTO.setFailed(total - passed);
        
        // 转换职位分布数据为前端所需格式
        List<PositionData> positionDataList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : positionMap.entrySet())
        {
            positionDataList.add(new PositionData(entry.getKey(), entry.getValue()));
        }
        statisticsDTO.setPositionData(positionDataList);
        
        return statisticsDTO;
    }
}
